<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="./css/reset.css"/>
  <link rel="stylesheet" href="./css/index.css"/>
  <link rel="stylesheet" href="./css/fonts/iconfont.css"/>
  <title>智能门锁</title>
</head>
<body>
  <div class="device-wrapper">
    <!-- 门锁信息 -->
    <section class="door-control-body">
    </section>
    <!-- 门锁模板 -->
    <script id="lockInfoTpl" type="text/html">
      {{if !$data.connected}}
        <p class="battery-status-icon">
          <span class="iconfont icon-battery battery f-green"></span>
          <span class="battery-text">— —</span>
        </p>
        <div class="door-status-img">
          <div class="circle-gray">
            <div class="circle-inner-gray">
              <span class="iconfont icon-lockclose gray-icon"></span>
            </div>
          </div>
          <p class='current-status'>门锁离线</p>
        </div>
      {{else if $data.info.name === 'dh.alarmType'}}
        <p class="battery-status-icon">
        {{if $data.info.value === '2'}}
          <span class="iconfont icon-batterylowpower battery f-red"></span>
          <span class="battery-text">欠压</span>
        {{else}}
          <span class="iconfont icon-battery battery f-green"></span>
          <span class="battery-text">正常</span>
        {{/if}}
        </p>
        <div class="door-status-img">
          <div class="circle-red">
            <div class="circle-inner-red">
            {{if $data.info.value === '2'}}
              <span class="iconfont icon-lowpower red-icon"></span>
            {{else if $data.info.value === '1'}}
              <span class="iconfont icon-alarm red-icon"></span>
            {{else}}
              <span class="iconfont icon-illegalopen red-icon"></span>
            {{/if}}
            </div>
          </div>
          <p class='current-status'>{{$data.info.value === '2' ? '低电压报警' : ($data.info.value === '1' ? '防拆报警' : '非法开锁')}}</p>
      </div>
      {{else}}
        <p class="battery-status-icon">
          <span class="iconfont icon-battery battery f-green"></span>
          <span class="battery-text">正常</span>
        </p>
        <div class="door-status-img">
          <div class="circle-green">
            <div class="circle-inner-green">
              <span class="iconfont icon-lockclose green-icon"></span>
            </div>
          </div>
        </div>
      {{/if}}
    </script>
    <!-- 门锁历史信息日期选择 -->
    <section class="door-history-status">
      <div class="date ">
        <input class="date-hook date-input" type="text" id="date-hook" readonly />
        <span class="week week-hook" id="week-hook"></span>
        <span class="iconfont icon-calendar calendar" id="calendar-hook" onclick="MENSUO.initDate()" ></span>
      </div>
      <div class="door-status-box">
      </div>
    </section>
    <!-- 门锁历史信息模板   {{if child.name === 'unlockWay' || child.name === 'dh.alarmType'}}   {{/if}}-->
    <script id="historyDataTpl" type="text/html">
      {{each list as item index}}
      <div class="status-item">
        <span class="time">{{formatDate(false, item.timeStampMs)}}</span>
        {{each item.params as child childInd}}
          {{if child.name === 'unlockWay' || child.name === 'dh.alarmType'}}
            <h2 class="reason">检测到{{filterParamName(child.name,child.value)}}</h2>
          {{/if}}
        {{/each}}
      </div>
      {{/each}}
    </script>
    <!-- 提示弹窗 -->
    <div id="toast" class="hide">
      <div class="toast-hook toast">
      </div>
    </div>
    <!-- 加载动画 -->
    <div id="loader" class="hide">
      <div class="spinner">
          <div class="double-bounce1"></div>
          <div class="double-bounce2"></div>
      </div>
    </div>
  </div>

  <!-- js 从这里开始 -->
  <script src="./javascript/template.js"></script>
  <script src="https://open.home.komect.com/jssdk/hejia-1.1.0.min.js"></script>
  <script src="./javascript/iScroll.js"></script>
  <script src="./javascript/Mdate.js"></script>
  <script src="./javascript/until.js"></script>
  <script>
    let historyParam = {}
    let startTime
    let endTime
    // const lockWay = 'unlockWay' // 开门方式
    // const alarmType = 'dh.alarmType' // 报警类型
    // 历史信息 今日的日期 和星期
    const MENSUO = {
      todayInfo: function () {
        console.log('今日信息')
      let str_date = formatDate()
      let str_week = getDay()
      let dateEl = document.querySelector('.date-hook')
      dateEl.value = str_date
      dateEl.dataset.year = str_date.split('/')[0]
      dateEl.dataset.month = str_date.split('/')[1]
      dateEl.dataset.day = str_date.split('/')[2]
      document.querySelector('.week-hook').innerHTML = str_week
      startTime = new Date().setHours(0, 0, 0, 0)
      endTime = new Date().setHours(23, 59, 59, 0)
      },
      initDate: function () {
        console.log('选择日期')
        new Mdate("calendar-hook", {
          acceptId: "date-hook",
          weekacceptId: 'week-hook',
          beginYear: "2018",
          beginMonth: "1",
          beginDay: "1",
          format: "-",
          callback:function(start, end) {
            getHistoryFun(start, end)
          }
        })
      },
      clientHeight: function () {
        console.log('高度')
        const clientHeight = document.documentElement.clientHeight;
        let statusBox = document.querySelector('.door-status-box')
        statusBox.style.height = clientHeight - 389 + 'px'
      }
    }
    MENSUO.todayInfo()
    MENSUO.clientHeight()
     /**
    * 门锁信息
    */
    var mensuoInfoData = {} // 门锁信息
    function fetchGetDeviceInfoFun (){
      return new Promise((resolve, reject) => {
        Hejia.getDeviceInfo(function (data){
          resolve(data)
        },function (msg){ // 失败回调
          reject(msg)
        })
      })
    }
    function fetchGetCurrentFun () {
      return new Promise ((resolve, reject) => {
        Hejia.getCurrentParam(function (device){
          resolve(device)
        }, function (msg, obj){
          reject(msg,obj)
        })
      })
    }
    /*
    * 获取在线离线状态 mensuoInfoData {connected: false, data: []}
    */
    async function _initFun (){
      try{
        let connected
        let res = await fetchGetDeviceInfoFun()
        // alert(`状态 ${JSON.stringify(res)}`)
        stopLoading()
        if (res && res.device) {
          connected = res.device.connected
          mensuoInfoData['connected'] = connected
          if (connected) {
            let result = await fetchGetCurrentFun()
            if (result['parameters']) {
              // alert(`返回 ${JSON.stringify(result['parameters'])}`)
              let resultLockInfoData = handleDataCon(result['parameters'])
              mensuoInfoData['info'] = resultLockInfoData
              let lockInfoHtml = template('lockInfoTpl',mensuoInfoData)
              document.querySelector('.door-control-body').innerHTML = lockInfoHtml
            }
            // 设备当前参数
            getHistoryFun() // 历史开门数据
          } else {
            let lockInfoHtml = template('lockInfoTpl',mensuoInfoData)
            document.querySelector('.door-control-body').innerHTML = lockInfoHtml
          }
        } 
      }catch (err){
        alert(err);
      }
    }

    function getHistoryFun (start, end) {
      // startLoading()
      startTime = start || startTime // 今日凌晨的时间戳
      endTime = end || endTime // 今日凌晨的时间戳
      Hejia.getHistoryParam({ startDate: startTime, endDate: endTime}, function (arr) {
        // alert(`返回2${JSON.stringify(arr)}`)
        let _arr = []
        if (arr && arr.length > 0) {
          arr.map((item, index) => {
            item.params.map((child, childInd) => {
              if (child.name === 'unlockWay' || child.name === 'dh.alarmType'){
                _arr.push(item)
              }
            })
          })
          _arr.reverse()
          historyParam['list'] = _arr
          let historyHtml = template('historyDataTpl',historyParam)
          document.querySelector('.door-status-box').innerHTML = historyHtml
        }
      }, function (msg, obj){
        showToast(`没有开门信息`)
        MENSUO.todayInfo()
      });
    }


    // 初始化
    Hejia.ready(function(){
        // alert('初始化')
        startLoading()
        //门锁目前的状态
        _initFun()
        setInterval(() => {
          _initFun()
        }, 5* 1000)
      });
      
    // function fetchGetDeviceInfoFun2 (){
    //   return new Promise((resolve, reject) => {
    //     var data = {
    //     "device": {
    //     "lastDataReceivedDate": "2018-05-09T14:21:09+08:00",
    //     "lastDataReceivedDateMs": 1525846869000,
    //     "lastMeasureDate": "2018-05-09T14:21:09+08:00",
    //     "lastMeasureDateMs": 1525846869000,
    //     "connected": true}
    //     }
    //     resolve(data)
    //   })
    // }
    // function fetchGetCurrentFun2 () {
    //   return new Promise ((resolve, reject) => {
    //     var data = {
    //         "parameters":[{ name: 'dh.alarmType', value: '1',lastUpdateTimeMs: 1528949992879},{name: 'connectionStatus',value: '1', lastUpdateTimeMs: 1528947932899}, {name: 'unlockWay',lastUpdateTimeMs: 1528947932899}]
    //         }
    //     resolve(data)
    //   })
    // }
    // async function _initFun2 (){
    //   try{
    //     let connected
    //     let res = await fetchGetDeviceInfoFun2()
    //     stopLoading()
    //     if (res && res.device) {
    //       connected = res.device.connected
    //       mensuoInfoData['connected'] = connected
    //       if (connected) {
    //         let result = await fetchGetCurrentFun2()
    //         console.log(result)
    //         if (result['parameters'].length > 0) {
    //           alert(`返回 ${JSON.stringify(result['parameters'])}`)
    //           let resultLockInfoData = handleDataCon(result['parameters'])
    //           mensuoInfoData['info'] = resultLockInfoData
    //           let lockInfoHtml = template('lockInfoTpl',mensuoInfoData)
    //           document.querySelector('.door-control-body').innerHTML = lockInfoHtml
    //         }
    //         // 设备当前参数
    //         // getHistoryFun() // 历史开门数据
    //       } else {
    //         let lockInfoHtml = template('lockInfoTpl',mensuoInfoData)
    //         document.querySelector('.door-control-body').innerHTML = lockInfoHtml
    //       }
    //     } 
    //   }catch (err){
    //     alert(err);
    //   }
    // }
    // _initFun2()

    // let resultLockInfoData = handleDataCon(data)
    // mensuoInfoData['connected'] = false
    // mensuoInfoData['info'] = resultLockInfoData
    // console.log(mensuoInfoData)
    // let lockInfoHtml = template('lockInfoTpl',mensuoInfoData)
    // document.querySelector('.door-control-body').innerHTML = lockInfoHtml

    // historyParam = {
    //   list: [
    //     {timeStampMs: 1528947932879,params:[{name: 'unlockWay', value: '1'}, {name: 'dh.alarmType', value: '2'}, {name: 'connectionStatus', value: '1'}]},
    //     {timeStampMs: 1528947945896,params:[{name: 'unlockWay', value: '1'}, {name: 'dh.alarmType', value: '0'},{name: 'connectionStatus', value: '0'}]},
    //     {timeStampMs: 1528948932865,params:[{name: 'unlockWay', value: '0'},{name: 'unlockWay', value: '0'}, {name: 'connectionStatus', value: '1'}]},
    //     {timeStampMs: 1528947932865,params:[{name: 'dh.alarmType', value: '1'}]},
    //     {timeStampMs: 1528947932865,params:[{name: 'connectionStatus', value: '1'}]}
      
    // ]}
    // let historyHtml = template('historyDataTpl',historyParam)
    // document.querySelector('.door-status-box').innerHTML = historyHtml
    

  </script>
</body>
</html>